package com.demo.function.lambda;

import com.alibaba.fastjson.JSON;
import com.demo.model.entity.es.OrderHeader;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 测试lambda断言
 * @author K
 */
@Slf4j
public class LambdaPredicate {

    /**
     * 对象集合有相同值去重
     */
    public void distinct() {
        List<OrderHeader> list = new ArrayList<>();

        OrderHeader orderHeader = new OrderHeader();
        orderHeader.setOrderSn("aa");
        list.add(orderHeader);

        orderHeader = new OrderHeader();
        orderHeader.setOrderSn("aa");
        list.add(orderHeader);

        orderHeader = new OrderHeader();
        orderHeader.setOrderSn("bb");
        list.add(orderHeader);

        List<OrderHeader> people = list.stream().filter(distinctByKey(OrderHeader::getOrderSn)).collect(Collectors.toList());
        log.info("LambdaPredicate.distinct:{}", JSON.toJSONString(people));
    }

    private <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        // 这个函数将应用到每一个item
        Map<Object, Boolean> seen = new ConcurrentHashMap<>(16);
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}
